package com.jzt.gateway.service;

import com.jzt.gateway.config.JwtTokenConfig;
import com.jzt.gateway.model.AccountInfo;
import com.jzt.gateway.utils.DateTimeUtils;
import com.jzt.gateway.utils.JwtTokenUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 作者：lizw <br/>
 * 创建时间：2020/06/18 14:29 <br/>
 */
@Service
@Slf4j
public class AuthService {
//    @Autowired
//    private UnionUserDao unionUserDao;
//    @Autowired
//    private AccountDao accountDao;

    /**
     * token 认证实现
     */
    public AuthRes auth(List<String> tokens, JwtTokenConfig jwtTokenConfig) {
        Jws<Claims> jws = null;
        AccountInfo accountInfo = null;
        for (String token : tokens) {
            try {
                jws = JwtTokenUtils.getClaimsJws(token, jwtTokenConfig);
                accountInfo = JwtTokenUtils.getAccountInfo(jws);
                break;
            } catch (Exception e) {
                log.warn("认证失败", e);
            }
        }
        String newToken = null;
        if (accountInfo != null) {
            // 过期刷新处理
            Date expDate = jws.getBody().getExpiration();
            if (expDate != null) {
                expDate = DateTimeUtils.addMinutes(expDate, -3);
            }
            if (expDate == null || expDate.compareTo(new Date()) <= 0) {
                try {
                    newToken = JwtTokenUtils.createToken(accountInfo, jwtTokenConfig);
                } catch (Exception e) {
                    log.warn("生成新Token失败", e);
                }
            }
            // 访问刷新处理
            Date issuedAt = jws.getBody().getIssuedAt();
            if (issuedAt != null) {
                issuedAt = DateTimeUtils.addMinutes(issuedAt, 6);
            }
            if (issuedAt == null || issuedAt.compareTo(new Date()) <= 0) {
                try {
                    newToken = JwtTokenUtils.createToken(accountInfo, jwtTokenConfig);
                } catch (Exception e) {
                    log.warn("生成新Token失败", e);
                }
            }
        }
        return new AuthRes(accountInfo, newToken);
    }

    @Getter
    public static class AuthRes {
        /**
         * 账号信息
         */
        private final AccountInfo accountInfo;
        /**
         * 新Token，当前Token块过期就会生成新的Token
         */
        private final String newToken;

        public AuthRes(AccountInfo accountInfo, String newToken) {
            this.accountInfo = accountInfo;
            this.newToken = newToken;
        }
    }
}
